﻿using System;
using System.IO;
using Presentation;
using System.Xml;

namespace Infrastructure
{
    public class LoggerHtml: ILogger
    {
        public string htmlLogFileName;
        private XmlDocument xmlLog;

        public string getLogFileName()
        {
            return htmlLogFileName;
        }

        public LoggerHtml(string logFileName = "log.html")
        {
            htmlLogFileName = logFileName;

            xmlLog = new XmlDocument();

            var html = AppendChild("html", xmlLog);
            var head = AppendChild("head", html);

            var title = AppendChild("title", head);
            title.InnerText = htmlLogFileName;

            AppendChild("body", html);

            xmlLog.Save(htmlLogFileName);
        }

        private XmlElement AppendChild(string tag, XmlNode node)
        {
            return node.AppendChild(xmlLog.CreateElement(tag)) as XmlElement;
        }

        public void Write(string message)
        {
            var body = xmlLog.GetElementsByTagName("body")[0];
            var pre = AppendChild("pre", body);
            var time = DateTime.Now.ToString("HH:mm:ss");
            pre.InnerText += time + " : " + message;

            xmlLog.Save(htmlLogFileName);
        }

        public string Read()
        {
            var text = "";
            using (var reader = new StreamReader(htmlLogFileName))
            {
                while (!reader.EndOfStream)
                {
                    text += reader.ReadLine();
                }
                reader.Close();
            }
            return text;
        }
    }
}
